package com.sanji.sjmallmodule.main;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.goods.GoodsBean;
import com.sanji.sjmallmodule.goods.GoodsDetailsActivity;
import com.sanji.sjmallmodule.goods.SelectTypeActivity;
import com.sanji.sjmallutils.JsonParseUtil;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.BannerPagerView;
import com.sanji.sjmallwidget.BannerPointView;
import com.sanji.sjmallwidget.MyGrideView;
import com.umeng.analytics.MobclickAgent;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sanji.sjmallconfig.ConfigAPI.MAIN_BANNER_URL;

public class MainFragment extends Fragment implements View.OnClickListener, NoHttpListener {
    @BindView(R.id.fragment_main_layout)
    LinearLayout mLayout;
    @BindView(R.id.banner_pager_view)
    BannerPagerView mBannerPagerView;
    @BindView(R.id.banner_point_view)
    BannerPointView mPointView;
    @BindView(R.id.fragment_main_today_top_gride)
    MyGrideView todayGride;
    @BindView(R.id.fragment_main_week_top_gride)
    MyGrideView weekGride;
    @BindView(R.id.fragment_main_month_top_gride)
    MyGrideView monthGride;
    @BindView(R.id.fragment_main_search_img)
    ImageView fragmentMainSearchImg;
    @BindView(R.id.fragment_main_edit)
    EditText mainSearchEdit;
    String searchName;
    @BindView(R.id.fragment_main_today_top)
    TextView todayTitle;
    @BindView(R.id.fragment_main_week_top)
    TextView weekTitle;
    @BindView(R.id.fragment_main_month_top)
    TextView monthTitle;
    @BindView(R.id.search_frame)
    FrameLayout searchFrame;
    private List<ImageView> imageList;
    private int[] imageResIDs;
    private ViewPagerAdapter viewPagerAdapter;
    private List<GoodsBean> todayData;
    private List<GoodsBean> weekData;
    private List<GoodsBean> monthData;
    MainGrideAdapter todayAdapter;
    MainGrideAdapter weekAdapter;
    MainGrideAdapter monthAdapter;

    private boolean isPlaying = false;
    private View rootView;
    private Request<JSONObject> request;
    private int type;//类型
    List<BannerBean> bannerList;
    //
    private PopupWindow btnWindow;//手机、配件的popWindow
    TextView searchPartTv;
    TextView searchPhoneTv;
    private Boolean isPopShow;
    private String searchParam = "";//手机、配件的参数
    Intent intent = null;

    private SharePreferenceUtil myShare = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_main, null);
            ButterKnife.bind(this, rootView);
            initView();
        }
        ButterKnife.bind(this, rootView);
        myShare = MallApplication.getApplication().myShare;
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (bannerList.size() == 0) {
            addHeader();
        }
        onItemClick();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        imageList = new ArrayList<>();
        todayData = new ArrayList<>();
        weekData = new ArrayList<>();
        monthData = new ArrayList<>();
        bannerList = new ArrayList<>();
        todayAdapter = new MainGrideAdapter(getActivity(), todayData);
        monthAdapter = new MainGrideAdapter(getActivity(), monthData);
        weekAdapter = new MainGrideAdapter(getActivity(), weekData);
        todayGride.setAdapter(todayAdapter);
        weekGride.setAdapter(weekAdapter);
        monthGride.setAdapter(monthAdapter);
        fragmentMainSearchImg.setOnClickListener(this);
        //网络请求数据
        if (todayData.size() == 0) {
            getPhoneData();
        }
        //点击回车以后弹出popwindow
        mainSearchEdit.setOnKeyListener(onkey);
        mainSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                return (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    View.OnKeyListener onkey = new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                //弹出搜索框
                showBtnPop();
            }
            return false;
        }
    };

    //加载头部的广告
    private void addHeader() {
        //网络请求
        request = NoHttp.createJsonObjectRequest(ConfigAPI.MAIN_BANNER_URL, RequestMethod.GET);
        request.setCancelSign(ConfigAPI.MAIN_BANNER_URL.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), ConfigAPI.MAIN_BANNER_URL.hashCode(), request, this, true, true);
    }

    /**
     * 网络请求手机数据
     */
    public void getPhoneData() {
        request = NoHttp.createJsonObjectRequest(ConfigAPI.GOODS_HOT_URL, RequestMethod.GET);
        request.setCancelSign(ConfigAPI.GOODS_HOT_URL.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), ConfigAPI.GOODS_HOT_URL.hashCode(), request, this, true, true);
    }

    /**
     * 点击事件
     */
    public void onItemClick() {
        monthGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GoodsBean phoneBean = (GoodsBean) monthAdapter.getItem(i);
                intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("goodsCode", phoneBean.getGoodsCode());
                intent.putExtra("goodsType", "sj");
                startActivity(intent);

            }
        });
        weekGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GoodsBean phoneBean = (GoodsBean) weekAdapter.getItem(i);
                intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("goodsCode", phoneBean.getGoodsCode());
                intent.putExtra("goodsType", "sj");
                startActivity(intent);
            }
        });
        todayGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GoodsBean phoneBean = (GoodsBean) todayAdapter.getItem(i);
                intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                intent.putExtra("goodsCode", phoneBean.getGoodsCode());
                intent.putExtra("goodsType", "sj");
                startActivity(intent);
            }
        });
    }


    @Override
    public void onPause() {
        isPlaying = false;
        mBannerPagerView.stopPlay();
        MobclickAgent.onPageEnd("MainFragment");
        super.onPause();
    }

    @Override
    public void onResume() {
        if (!isPlaying) {
            mBannerPagerView.startPlay();
        }
        MobclickAgent.onPageStart("MainFragment");
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_main_search_img:
                showBtnPop();
                break;
        }
    }

    @Override
    public void onSuccessed(int what, Response response) {
        JSONObject json = (JSONObject) response.get();
        String status = json.optString(ConfigConts.STATUS_STRING);
        if (status.equals(ConfigConts.STATUS_SUCCESS)) {
            if (what == ConfigAPI.GOODS_HOT_URL.hashCode()) {
                JSONObject object = json.optJSONObject("result");
                JSONArray weekArray = object.optJSONArray("week");
                JSONArray monthArray = object.optJSONArray("month");
                JSONArray dayArray = object.optJSONArray("day");
                if (null == dayArray || dayArray.length() == 0) {
                    todayTitle.setVisibility(View.GONE);
                } else {
                    todayTitle.setVisibility(View.VISIBLE);
                    todayData = JsonParseUtil.hotGoodsParse(dayArray);
                }
                if (null == weekArray || weekArray.length() == 0) {
                    weekTitle.setVisibility(View.GONE);
                } else {
                    weekTitle.setVisibility(View.VISIBLE);
                    weekData = JsonParseUtil.hotGoodsParse(weekArray);
                }
                if (null == monthArray || monthArray.length() == 0) {
                    monthTitle.setVisibility(View.GONE);
                } else {
                    monthTitle.setVisibility(View.VISIBLE);
                    monthData = JsonParseUtil.hotGoodsParse(monthArray);
                }
                todayAdapter.notifyAdapter(todayData);
                weekAdapter.notifyAdapter(weekData);
                monthAdapter.notifyAdapter(monthData);

            } else if (what == MAIN_BANNER_URL.hashCode()) {
                JSONObject result = json.optJSONObject("result");
                //首页轮播图
                JSONArray resultArray = result.optJSONArray("switchPicList");
                for (int i = 0; i < resultArray.length(); i++) {
                    try {
                        JSONObject object = resultArray.getJSONObject(i);
                        String imgUrl = object.optString("imgUrl");
                        String goodsId = object.optString("goodsNum");
                        String type = object.optString("type");
                        BannerBean bean = new BannerBean(goodsId, imgUrl, type);
                        bannerList.add(bean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                mBannerPagerView.initBannerData(mPointView, bannerList, true, 0);
                mBannerPagerView.startPlay();
                isPlaying = true;

                //运费标准
                JSONObject shipCostJson = result.optJSONObject("shipCostCondition");
                JSONObject phone = shipCostJson.optJSONObject("phone");
                int phoneNum = phone.optInt("count");
                myShare.put(ConfigConts.FARE_PHONE_NUM, phoneNum);
                int phoneFre = phone.optInt("totalPrice", 0);
                myShare.put(ConfigConts.FARE_PHONE_PRICE, phoneFre);
                JSONObject parts = shipCostJson.optJSONObject("parts");
                int partsNum = parts.optInt("count");
                myShare.put(ConfigConts.FARE_PARTS_NUM, partsNum);
                int partsFre = parts.optInt("totalPrice", 0);
                myShare.put(ConfigConts.FARE_PARTS_PRICE, partsFre);
                int shopCost = shipCostJson.optInt("shipCost", 0);
                myShare.put(ConfigConts.FARE_COST, shopCost);

            }
            mLayout.setVisibility(View.VISIBLE);
        } else {
            String errorMsg = json.optString(ConfigConts.ERRORMSG);
            Tools.toastTools(getActivity(), errorMsg);
        }

    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(getActivity(), getString(R.string.request_false));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        request.cancel();
    }

    /**
     * 弹出搜手机、配件的popWindow
     */
    public void showBtnPop() {
        if (null == btnWindow) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_phone_part, null);
            searchPartTv = (TextView) view.findViewById(R.id.search_part);
            searchPhoneTv = (TextView) view.findViewById(R.id.search_phone);
            btnWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            //实例化一个colorDraable颜色为透明色
            ColorDrawable dw = new ColorDrawable(0xb0000000);
            btnWindow.setBackgroundDrawable(dw);
            btnWindow.setFocusable(true);
        }
        btnWindow.showAsDropDown(searchFrame);
        isPopShow = true;
        setPopupViews(isPopShow, fragmentMainSearchImg);
        searchPartTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnWindow.dismiss();
                isPopShow = false;
                setPopupViews(isPopShow, fragmentMainSearchImg);
                searchParam = "";
                searchName = mainSearchEdit.getText().toString().trim();

                Intent intent = new Intent(getActivity(), SelectTypeActivity.class);
                intent.putExtra("intentType", ConfigConts.MULTIPLE_PART);
                if (TextUtils.isEmpty(searchName)) {
                    Tools.toastTools(getActivity(), getString(R.string.search_content));
                } else {
                    intent.putExtra("selectParam", searchName);
                    startActivity(intent);
                }
            }
        });
        searchPhoneTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnWindow.dismiss();
                isPopShow = false;
                setPopupViews(isPopShow, fragmentMainSearchImg);
                searchParam = "";
                searchName = mainSearchEdit.getText().toString().trim();
                Intent intent = new Intent(getActivity(), SelectTypeActivity.class);
                intent.putExtra("intentType", ConfigConts.MULTIPLE_PHONE);
                if (TextUtils.isEmpty(searchName)) {
                    Tools.toastTools(getActivity(), getString(R.string.search_content));
                } else {
                    intent.putExtra("selectParam", searchName);
                    startActivity(intent);
                }
            }
        });
        btnWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isPopShow = false;
                setPopupViews(isPopShow, fragmentMainSearchImg);
            }
        });
    }

    /**
     * 修改popup相应的指示布局
     */
    private void setPopupViews(boolean flag, ImageView imageView) {
        if (flag) {
            imageView.setImageResource(R.mipmap.select_down);
        } else {
            imageView.setImageResource(R.mipmap.search_imag);
        }
    }

}
